/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web.member;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.sys.dao.member.MemberDao;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.entity.business.Business;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.service.business.BusinessService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.member.Member;
import com.thinkgem.jeesite.modules.sys.service.member.MemberService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 报警表Controller
 * @author jin
 * @version 2018-04-10
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/member/member")
public class MemberController extends BaseController {

	@Autowired
	private MemberService memberService;
	@Autowired
	private SystemService systemService;
    @Autowired
    private BusinessService businessService;
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private OfficeService officeService;
	
	@ModelAttribute
	public Member get(@RequestParam(required=false) String id) {
		Member entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = memberService.get(id);
		}
		if (entity == null){
			entity = new Member();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:member:member:view")
	@RequestMapping(value = {"list", ""})
	public String list(Member member, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Member> page = memberService.findPage(new Page<Member>(request, response), member); 
		model.addAttribute("page", page);
		return "modules/sys/member/memberList";
	}

	@RequiresPermissions("sys:member:member:view")
	@RequestMapping(value = "form")
	public String form(Member member, Model model) {
		model.addAttribute("member", member);
		return "modules/sys/member/memberForm";
	}

	@RequiresPermissions("sys:member:member:edit")
	@RequestMapping(value = "save")
	public String save(Member member, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, member)){
			return form(member, model);
		}
		if(member.getIdCard()!=null || member.getIdCard().length()!=0){
			String idcard = member.getIdCard();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			Date date = new Date();
			String dyear =  sdf.format(date);
			String year = idcard.substring(6,10);
			String sex = idcard.substring(16,17);
			int sexnum = (Integer.valueOf(sex)) % 2;
			int age = Integer.valueOf(dyear) - Integer.valueOf(year);
			if(sexnum == 1){
				member.setSex("1");
			}if(sexnum == 0){
				member.setSex("2");
			}
			member.setAge(String.valueOf(age));
		}
		memberService.save(member);
		addMessage(redirectAttributes, "保存报警成功");
		return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
	}
	
	@RequiresPermissions("sys:member:member:edit")
	@RequestMapping(value = "delete")
	public String delete(Member member, RedirectAttributes redirectAttributes) {
		memberService.delete(member);
		addMessage(redirectAttributes, "删除报警成功");
		return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
	}


//	@RequiresPermissions("sys:member:member:view")
//	@RequestMapping(value = "export", method= RequestMethod.POST)
//	public String exportFile(Member member, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
//		try {
//			String fileName = "用户数据"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
//			Page<Member> page = systemService.findUser(new Page<Member>(request, response, -1), member);
//			new ExportExcel("用户数据", Member.class).setDataList(page.getList()).write(response, fileName).dispose();
//			return null;
//		} catch (Exception e) {
//			addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
//		}
//		return "redirect:" + adminPath + "/sys/user/list?repage";
//	}

	@RequestMapping(value = "checkUser")
	public String checkUser(String id,Model model,HttpServletRequest request, HttpServletResponse response,User user){
		Member member = memberService.get(id);
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		model.addAttribute("page", page);
		model.addAttribute("member",member);
		return "modules/sys/member/checkUser";
	}
    @ResponseBody
	@RequestMapping(value = "saveKf")
    public Object saveKf(Business business){
       String ss = business.getKfId();
       String dd = business.getMemberId();
       if(ss != null){
       	   business.setJdTime(new Date());
       	   business.setYjStatic("1");
       	   business.setCsFlag("0");
           businessService.save(business);
           return true;
       }else {return false;}
    }

	/**
	 * 导出用户数据
	 * @param member
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(Member member, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "报警用户数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<Member> page = memberService.findUser(new Page<Member>(request, response, -1), member);
			new ExportExcel("用户数据", Member.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
	}

	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Member> list = ei.getDataList(Member.class);
			for (Member member : list){
				try{
//					if ("true".equals(checkLoginName("", user.getLoginName()))){
//						member.setPassword(SystemService.entryptPassword("123456"));

					if("0".equals(memberService.checkIdCard(member.getIdCard()))){
						if(member.getDqName()!= null || member.getDqName().length()!=0) {
							member.setDq(officeService.getOfficeId(member.getDqName()));
						}
						if(member.getIdCard()!=null || member.getIdCard().length()!=0){
							String idcard = member.getIdCard();
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
							Date date = new Date();
							String dyear =  sdf.format(date);
							String year = idcard.substring(6,10);
							String sex = idcard.substring(16,17);
							int sexnum = (Integer.valueOf(sex)) % 2;
							int age = Integer.valueOf(dyear) - Integer.valueOf(year);
							if(sexnum == 1){
								member.setSex("1");
							}if(sexnum == 0){
								member.setSex("2");
							}
							member.setAge(String.valueOf(age));
						}
						BeanValidators.validateWithException(validator, member);
						memberService.save(member);
						successNum++;
					}else{
						failureMsg.append("<br/>该用户身份证 "+member.getIdCard()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>姓名 "+member.getName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
//
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "预警客户数据导入模板.xlsx";
			List<Member> list = Lists.newArrayList(); list.add(new Member());
			new ExportExcel("预警客户数据", Member.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
	}


}